package com.xyh.transaction.utils;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class AmountConverter {

    private static final String[] NUMBERS = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
    private static final String[] UNIT = {"", "十", "百", "千", "万", "十", "百", "千", "亿"};

    public static String convertToChinese(BigDecimal amount) {
        StringBuilder result = new StringBuilder();

        // 将金额转换为字符串并去掉小数部分
        String amountStr = amount.setScale(2, RoundingMode.HALF_UP).toString();
        String integerPart = amountStr.split("\\.")[0];
        String decimalPart = amountStr.split("\\.")[1];

        // 处理整数部分
        int length = integerPart.length();
        boolean zeroFlag = false; // 用于标记是否需要在"零"后添加单位

        for (int i = 0; i < length; i++) {
            int digit = integerPart.charAt(i) - '0';
            if (digit != 0) {
                if (zeroFlag) {
                    result.append(NUMBERS[0]);
                    zeroFlag = false;
                }
                result.append(NUMBERS[digit]).append(UNIT[length - i - 1]);
            } else {
                zeroFlag = true;
            }
        }

        // 如果没有整数部分，加入“零”
        if ("0".equals(integerPart)) {
            result.append(NUMBERS[0]);
        }

        result.append("元");

        // 处理小数部分
        if (!"00".equals(decimalPart)) {
            result.append(NUMBERS[decimalPart.charAt(0) - '0']).append("角");
            if (decimalPart.charAt(1) != '0') {
                result.append(NUMBERS[decimalPart.charAt(1) - '0']).append("分");
            }
        } else {
            result.append("整");
        }

        return result.toString();
    }

    public static void main(String[] args) {
        BigDecimal amount = new BigDecimal("3180.00");
        System.out.println(convertToChinese(amount)); // 输出：叁仟捌佰元整
    }
}
